<template>
  <div class="my-farms">
    <el-container>
      <el-header>
        <div class="header-content">
          <div class="header-left">
            <el-button type="primary" @click="router.push('/')">
              <el-icon><ArrowLeft /></el-icon>
              返回主页
            </el-button>
          </div>
          <div class="header-center">
            <h2>我的植物园</h2>
          </div>
          <div class="header-right">
            <el-button type="success" @click="router.push('/create-farm')">
              <el-icon><Plus /></el-icon>
              创建农场
            </el-button>
          </div>
        </div>
      </el-header>
      <el-main>
        <div class="farms-grid">
          <el-card v-for="farm in farms" :key="farm.farmId" class="farm-card">
            <div class="farm-image">
              <el-image 
                :src="getPrimaryImage(farm.farmImages)"
                fit="cover"
              />
              <div class="farm-status" :class="getStatusClass(farm.statusId)">
                {{ getStatusText(farm.statusId) }}
              </div>
            </div>
            <div class="farm-info">
              <h3>{{ farm.farmName }}</h3>
              <p class="farm-address">地址：{{ farm.farmAddress }}</p>
              <p class="subsidy-amount" v-if="farm.appliedSubsidyAmount">
                申请补贴：¥{{ farm.appliedSubsidyAmount }}
              </p>
              <div class="farm-footer">
                <span class="created-time">创建于: {{ formatDate(farm.createdAt) }}</span>
                <el-button 
                  type="primary" 
                  @click="enterFarm(farm)"
                >
                  进入农场
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Plus } from '@element-plus/icons-vue'
import { getUserFarms } from '@/api/farms'

const router = useRouter()
const farms = ref([])

// 获取主图
const getPrimaryImage = (images) => {
  if (!images || images.length === 0) {
    return '/default-farm.jpg'
  }
  const primaryImage = images.find(img => img.isPrimary === 1)
  return primaryImage ? primaryImage.imageUrl : images[0].imageUrl
}

// 获取农场状态文本
const getStatusText = (statusId) => {
  switch (statusId) {
    case 1:
      return '申请中'
    case 3:
      return '已拒绝'
    case 0:
      return '创建中'
    case 2:
      return '营业中'
    default:
      return '未知状态'
  }
}

// 获取状态样式类
const getStatusClass = (statusId) => {
  switch (statusId) {
    case 1:
      return 'status-pending'    // 申请中 - 蓝色
    case 3:
      return 'status-rejected'   // 已拒绝 - 红色
    case 0:
      return 'status-creating'   // 创建中 - 黄色
    case 2:
      return 'status-operating'  // 营业中 - 绿色
    default:
      return ''
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知时间'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 进入农场
const enterFarm = (farm) => {
  router.push({
    path: `/farm/detail/${farm.farmId}`,
    query: {
      userId: farm.userId
    }
  })
}

// 加载农场数据
const loadFarms = async () => {
  try {
    console.log('开始获取农场列表...')
    const res = await getUserFarms()
    console.log('获取农场列表响应:', res)
    
    // 处理直接返回数组的情况
    if (Array.isArray(res)) {
      console.log('获取成功，农场数据:', res)
      farms.value = res
      if (farms.value.length === 0) {
        console.log('农场列表为空')
        ElMessage.info('暂无农场数据')
      }
      return
    }
    
    // 处理返回对象的情况
    if (res.success) {
      console.log('获取成功，农场数据:', res.data)
      farms.value = res.data || []
      if (farms.value.length === 0) {
        console.log('农场列表为空')
        ElMessage.info('暂无农场数据')
      }
    } else {
      console.log('获取失败，错误信息:', res.message)
      ElMessage.error(res.message || '获取农场列表失败')
      farms.value = []
    }
  } catch (error) {
    console.error('获取农场列表发生错误:', error)
    console.error('错误详情:', error.response?.data)
    console.error('错误状态:', error.response?.status)
    ElMessage.error('获取农场列表失败')
    farms.value = []
  }
}

onMounted(() => {
  loadFarms()
})
</script>

<style scoped>
.my-farms {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  padding: 0;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 20px;
}

.header-center {
  flex: 1;
  text-align: center;
}

.header-center h2 {
  margin: 0;
  color: #409EFF;
}

.el-main {
  padding: 20px;
  margin-top: 60px;
}

.farms-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
}

.farm-card {
  transition: transform 0.3s ease;
  overflow: hidden;
  border-radius: 8px;
}

.farm-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.farm-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.farm-image .el-image {
  width: 100%;
  height: 100%;
}

.farm-status {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 12px;
  border-radius: 4px;
  color: white;
  font-weight: bold;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.status-pending {
  background-color: #409EFF;  /* 申请中 - 蓝色 */
}

.status-rejected {
  background-color: #F56C6C;  /* 已拒绝 - 红色 */
}

.status-creating {
  background-color: #E6A23C;  /* 创建中 - 黄色 */
}

.status-operating {
  background-color: #67C23A;  /* 营业中 - 绿色 */
}

.farm-info {
  padding: 20px;
}

.farm-info h3 {
  margin: 0 0 10px 0;
  font-size: 20px;
  color: #303133;
}

.farm-address {
  color: #606266;
  margin: 8px 0;
  font-size: 14px;
}

.subsidy-amount {
  color: #F56C6C;
  margin: 8px 0;
  font-size: 14px;
  font-weight: bold;
}

.farm-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #EBEEF5;
}

.created-time {
  color: #909399;
  font-size: 13px;
}
</style> 